package com.ls.service.impl;

import com.ls.entity.Event;
import com.ls.entity.LoginTicket;
import com.ls.entity.User;
import com.ls.event.EventProducer;
import com.ls.mapper.UserMapper;
import com.ls.service.UserService;
import com.ls.util.CommunityConstant;
import com.ls.util.CommunityUtil;
import com.ls.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author ls
 */
@Service
public class UserServiceImpl implements UserService, CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // @Autowired
    // private LoginTicketMapper loginTicketMapper;

    @Value("${community.path.domain}")
    private String domain;

    @Override
    public User queryUserById(int id) {
        User user = getCacheUser(id);
        if (user == null) {
            user = initCacheUser(id);
        }
        return user;
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "账号不能为空!");
            return map;
        }

        //验证用户名
        User u = userMapper.queryUserByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该用户名已存在!");
            return map;
        }

        //验证邮箱
        u = userMapper.queryUserByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.addUser(user);

        // 触发 发送激活邮件事件，异步处理发送激活邮件
        Event event = new Event()
                .setTopic(TOPIC_EMAIL)
                .setUserId(user.getId());
        eventProducer.fireEvent(event);

        return map;
    }

    /**
     * 用户激活
     *
     * @param userId
     * @param code
     * @return
     */
    @Override
    public int activation(int userId, String code) {
        User user = userMapper.queryUserById(userId);
        // 已经激活
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            // 激活成功
            // 修改状态
            userMapper.updateStatus(userId, 1);
            clearCacheUser(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param expiredSeconds
     * @return
     */
    @Override
    public Map<String, Object> login(String username, String password, long expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        // 验证账号
        User user = userMapper.queryUserByName(username);
        if (user == null) {
            map.put("usernameMsg", "改账号不存在!");
            return map;
        }
        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "改账号未激活!");
            return map;
        }
        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        // loginTicketMapper.addLoginTicket(loginTicket);

        // 凭证存到redis中
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        // redis 会把对象序列化为 json 格式的字符串
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());

        return map;
    }

    @Override
    public void logout(String ticket) {
        // loginTicketMapper.updateLoginTicket(ticket,1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        if (loginTicket == null) {
            logger.info("ticket 为 [{}] 的用户登录信息不存在", ticket);
            return;
        }
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    @Override
    public LoginTicket queryLoginTicketByTicket(String ticket) {
        // return loginTicketMapper.queryLoginTicketByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    @Override
    public void updateUserHeaderUrl(int id, String headerUrl) {
        userMapper.updateHeader(id, headerUrl);
        clearCacheUser(id);
    }

    @Override
    public void updateUserPassword(int id, String password) {
        userMapper.updatePassword(id, password);
        clearCacheUser(id);
    }

    @Override
    public User queryUserByUsername(String username) {
        return userMapper.queryUserByName(username);
    }

    /*
    使用 redis 缓存数据
        1. 优先从缓存中取值
        2. 取不到时初始化缓存数据
        3. 数据变更时清除缓存数据
     */

    /**
     * 从 redis 缓存中获取用户
     *
     * @param userId 用户 id
     * @return 用户
     */
    private User getCacheUser(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 初始化用户到 redis 缓存
     *
     * @param userId 用户 id
     * @return 用户
     */
    private User initCacheUser(int userId) {
        User user = userMapper.queryUserById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 清除 redis 中缓存用户数据
     *
     * @param userId 用户 id
     */
    private void clearCacheUser(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.queryUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return AUTHORITY_ADMIN;
                    case 2:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

}
